'use strict';

const Controller = require('egg').Controller;

class AuthController extends Controller {
  // 用户注册
  async register() {
    const { ctx } = this;
    const { username, password, email, phone } = ctx.request.body;

    try {
      // 参数验证
      if (!username || !password || !email) {
        ctx.status = 400;
        ctx.body = {
          success: false,
          message: '用户名、密码和邮箱不能为空',
        };
        return;
      }

      // 密码长度验证
      if (password.length < 6) {
        ctx.status = 400;
        ctx.body = {
          success: false,
          message: '密码长度不能少于6位',
        };
        return;
      }

      // 邮箱格式验证
      const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
      if (!emailRegex.test(email)) {
        ctx.status = 400;
        ctx.body = {
          success: false,
          message: '邮箱格式不正确',
        };
        return;
      }

      // 创建用户
      const result = await ctx.service.user.create({
        username,
        password,
        email,
        phone,
      });

      ctx.status = 201;
      ctx.body = {
        success: true,
        message: '注册成功',
        data: {
          id: result.insertId,
        },
      };
    } catch (error) {
      ctx.status = 400;
      ctx.body = {
        success: false,
        message: error.message,
      };
    }
  }

  // 用户登录
  async login() {
    const { ctx } = this;
    const { username, password } = ctx.request.body;

    try {
      // 参数验证
      if (!username || !password) {
        ctx.status = 400;
        ctx.body = {
          success: false,
          message: '用户名和密码不能为空',
        };
        return;
      }

      // 查找用户
      const user = await ctx.service.user.findByUsername(username);
      if (!user) {
        ctx.status = 401;
        ctx.body = {
          success: false,
          message: '用户名或密码错误',
        };
        return;
      }

      // 验证密码
      const isValidPassword = await ctx.service.user.validatePassword(password, user.password);
      if (!isValidPassword) {
        ctx.status = 401;
        ctx.body = {
          success: false,
          message: '用户名或密码错误',
        };
        return;
      }

      // 检查用户状态
      if (user.status !== 'active') {
        ctx.status = 401;
        ctx.body = {
          success: false,
          message: '账户已被禁用',
        };
        return;
      }

      // 登录成功，返回用户信息
      ctx.body = {
        success: true,
        message: '登录成功',
        data: {
          user: {
            id: user.id,
            username: user.username,
            email: user.email,
            phone: user.phone,
            role: user.role,
            avatar: user.avatar,
          },
        },
      };
    } catch (error) {
      ctx.status = 500;
      ctx.body = {
        success: false,
        message: '服务器内部错误',
      };
    }
  }

  // 获取用户信息
  async getUserInfo() {
    const { ctx } = this;
    const { user_id } = ctx.request.query;

    try {
      if (!user_id) {
        ctx.status = 400;
        ctx.body = {
          success: false,
          message: '用户ID不能为空',
        };
        return;
      }

      const user = await ctx.service.user.findById(user_id);
      if (!user) {
        ctx.status = 404;
        ctx.body = {
          success: false,
          message: '用户不存在',
        };
        return;
      }

      ctx.body = {
        success: true,
        data: {
          id: user.id,
          username: user.username,
          email: user.email,
          phone: user.phone,
          role: user.role,
          avatar: user.avatar,
          status: user.status,
        },
      };
    } catch (error) {
      ctx.status = 500;
      ctx.body = {
        success: false,
        message: '服务器内部错误',
      };
    }
  }

  // 用户登出
  async logout() {
    const { ctx } = this;
    ctx.body = {
      success: true,
      message: '登出成功',
    };
  }

  // 更新用户个人信息
  async updateProfile() {
    const { ctx } = this;
    const user_id = ctx.state.user?.id;

    if (!user_id) {
      ctx.status = 401;
      ctx.body = { success: false, message: '请先登录' };
      return;
    }

    try {
      const data = ctx.request.body;
      await ctx.service.user.updateProfile(user_id, data);

      // 重新获取用户信息
      const user = await ctx.service.user.findById(user_id);
      delete user.password;

      ctx.body = {
        success: true,
        message: '个人信息更新成功',
        data: user,
      };
    } catch (error) {
      ctx.status = 400;
      ctx.body = { success: false, message: error.message };
    }
  }

  // 修改密码
  async changePassword() {
    const { ctx } = this;
    const user_id = ctx.state.user?.id;

    if (!user_id) {
      ctx.status = 401;
      ctx.body = { success: false, message: '请先登录' };
      return;
    }

    const { oldPassword, newPassword } = ctx.request.body;

    if (!oldPassword || !newPassword) {
      ctx.status = 400;
      ctx.body = { success: false, message: '请填写完整信息' };
      return;
    }

    if (newPassword.length < 6) {
      ctx.status = 400;
      ctx.body = { success: false, message: '新密码长度不能少于6位' };
      return;
    }

    try {
      await ctx.service.user.changePassword(user_id, oldPassword, newPassword);
      ctx.body = {
        success: true,
        message: '密码修改成功',
      };
    } catch (error) {
      ctx.status = 400;
      ctx.body = { success: false, message: error.message };
    }
  }

  // 获取用户统计信息
  async getUserStats() {
    const { ctx } = this;
    const user_id = ctx.state.user?.id;

    if (!user_id) {
      ctx.status = 401;
      ctx.body = { success: false, message: '请先登录' };
      return;
    }

    try {
      const stats = await ctx.service.user.getUserStats(user_id);
      ctx.body = {
        success: true,
        data: stats,
      };
    } catch (error) {
      ctx.status = 500;
      ctx.body = { success: false, message: '获取统计信息失败' };
    }
  }
}

module.exports = AuthController;